﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BFlatCompile.Nodes
{
	public class Ternary : Expression
	{
		public Expression Condition { get; private set; }
		public Expression TrueValue { get; private set; }
		public Expression FalseValue { get; private set; }
		public Token QuestionMarkToken { get; private set; }
		private Ternary(Expression condition, Expression trueValue, Expression falseValue, Token questionMarkToken)
		{
			this.Condition = condition;
			this.TrueValue = trueValue;
			this.FalseValue = falseValue;
			this.QuestionMarkToken = questionMarkToken;
		}

		public static Expression Create(Expression condition, Expression trueValue, Expression falseValue, Token questionToken)
		{
			while (true)
			{
				if (condition is BooleanNot)
				{
					condition = ((BooleanNot)condition).Expression;
					Expression t = trueValue;
					trueValue = falseValue;
					falseValue = t;
				}
				else if (condition is BooleanConstant)
				{
					if (((BooleanConstant)condition).Value)
					{
						return trueValue;
					}
					return falseValue;
				}
				else
				{
					break;
				}
			}

			return new Ternary(condition, trueValue, falseValue, questionToken);
		}

		public override void ResolveCode(Class c, Dictionary<object, object> parents)
		{
			this.Condition.ResolveCode(c, parents);
			this.TrueValue.ResolveCode(c, parents);
			this.FalseValue.ResolveCode(c, parents);
		}

		public override void ResolveClassToThis(Class c)
		{
			foreach (ICodeContainer code in new Consolidator().Add(this.Condition).Add(this.TrueValue).Add(this.FalseValue).List())
			{
				code.ResolveClassToThis(c);
			}
		}
	}
}
